package com.mini.gateway;

import com.mini.common.util.Base64Helper;
import com.mini.gateway.filter.ShortStateLoadBalancer;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import reactor.core.publisher.Mono;

/**
 * @author 小鱼儿
 * @date 2020/11/16 18:23
 */
@Configuration
public class GatewayConfig {


    @Bean
    public RouteLocator appRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/game/api/**")
                        .filters(f -> f.filter(new ShortStateLoadBalancer())
                                .modifyRequestBody(byte[].class, byte[].class, MediaType.APPLICATION_JSON_VALUE,
                                        (exchange, s) -> {
                                            byte[] array = Base64Helper.decryptAES(s);
                                            return Mono.just(array);
                                        }).modifyResponseBody(byte[].class, byte[].class, MediaType.APPLICATION_JSON_VALUE,
                                        (exchange, s) -> {
                                            return Mono.just(Base64Helper.encryptAES(s));
                                        })
                        )
                        .uri("sslb://game")
                        .id("game-route")
                ).route(r -> r.path("/game/authapi/**").filters(f -> f.modifyRequestBody(byte[].class, byte[].class, MediaType.APPLICATION_JSON_VALUE,
                        (exchange, s) -> {
                            byte[] array = Base64Helper.decryptAES(s);
                            return Mono.just(array);
                        }).modifyResponseBody(byte[].class, byte[].class, MediaType.APPLICATION_JSON_VALUE,
                        (exchange, s) -> {
                            return Mono.just(Base64Helper.encryptAES(s));
                        })).uri("lb://game").id("game-auth-route")).build();
    }
}
